package com.csinc.generate.core.make.impl;

import com.csinc.generate.core.make.IMake;
import com.csinc.generate.core.base.model.GenBeanEntity;
import com.csinc.generate.core.base.model.GenerationEntity;
import com.csinc.generate.core.base.model.TemplateModel;
import lombok.extern.slf4j.Slf4j;
import org.beetl.core.Configuration;
import org.beetl.core.GroupTemplate;
import org.beetl.core.Template;
import org.beetl.core.resource.StringTemplateResourceLoader;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 解析模板,生产代码
 * <url></>http://ibeetl.com/guide/</url>
 * Create By 郭金宝 on 2018/7/23.<br>
 */
@Slf4j
public class BeetlMakeImpl implements IMake {
    private static final StringTemplateResourceLoader resourceLoader = new StringTemplateResourceLoader();

    private static Configuration cfg;
    private static GroupTemplate gt;

    static {
        try {
            cfg = Configuration.defaultConfiguration();
            gt = new GroupTemplate(resourceLoader, cfg);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }


    public List<String> makeByTemplateModel(GenerationEntity generationEntity, GenBeanEntity tableEntity, List<TemplateModel> fileList) {
        List<String> renderList = new ArrayList<String>();
        Template t;
        for (TemplateModel file : fileList) {
//            log.info("获取到的模板是："+file.getFileModel().getFile());
            t = gt.getTemplate(file.getFileModel().getFile());
            t.binding(IMake.GEN_PARAMS, generationEntity);
            t.binding(IMake.TABLE_DETAIL, tableEntity);
//            StringWriter sw = new StringWriter();
//            t.renderTo(sw);
//            log.info("t.render() " + sw.toString());
            renderList.add(t.render());
        }
        return renderList;
    }

    @Override
    public List<String> make(GenerationEntity generationEntity, GenBeanEntity tableEntity, List<String> fileList) {
        List<String> renderList = new ArrayList<String>();
        Template t;
        for (String file : fileList) {
            t = gt.getTemplate(file);
            t.binding(IMake.GEN_PARAMS, generationEntity);
            t.binding(IMake.TABLE_DETAIL, tableEntity);
//            StringWriter sw = new StringWriter();
//            t.renderTo(sw);
//            log.info("t.render() " + sw.toString());
            renderList.add(t.render());
        }
        return renderList;
    }
}
